//
//  SingleGraphViewController.m
//  ClinicalCollections
//
//  Created by janakiraman gopinath on 3/9/13.
//  Copyright (c) 2013 GOPI. All rights reserved.
//

#import "SingleGraphViewController.h"
#import "CommonAPI.h"
@interface SingleGraphViewController ()

@property (weak, nonatomic) IBOutlet CPTGraphHostingView *graphView;

@end;

@implementation SingleGraphViewController

@synthesize chartType = _chartType;
@synthesize chartArray = _chartArray;
@synthesize chartTitle = _chartTitle;

-(void)setChartArray:(NSArray *)chartArray
{
    NSArray *arrayToBeSorted = [chartArray copy];
    
    _chartArray = [arrayToBeSorted sortedArrayUsingComparator:^NSComparisonResult(id first, id second) {
        NSDictionary *dict1 = (NSDictionary *)first;
        NSDictionary *dict2 = (NSDictionary *)second;
        NSArray *keys1 = [dict1 allKeys];
        NSArray *keys2 = [dict2 allKeys];
        NSString *string1 = keys1[0];
        NSString *string2 = keys2[0];
        
        return [string1 compare:string2 options:NSCaseInsensitiveSearch];
    }];
    
}

-(void)setCcvsCustomData:(CCVSGraphData *)ccvsCustomData
{
    self.chartType = ccvsCustomData.chartType;
    self.chartArray = ccvsCustomData.chartArray;
    self.chartTitle = ccvsCustomData.chartTitle;
    _ccvsCustomData = ccvsCustomData;
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [[self tableView] setFrame:CGRectMake(10, 550, 768, 150)];

}
- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if ([self.chartType isEqualToString:BAR_CHART]) {
        [self constructBarChart:self.graphView];
    }
    else if ([self.chartType isEqualToString:PIE_CHART]) {
        [self constructPieChart:self.graphView];
    }
}

-(NSArray *)removeTotalFromArray:(NSArray *) theDataArray
{
    NSMutableArray *dataArray = [theDataArray mutableCopy];
    
    int totalPosition = -1;
    for (int i=0; i< [dataArray count]; i++)
    {
        NSDictionary *element = [dataArray objectAtIndex:i];
        if ([[element allKeys][0] isEqualToString:@"Total"]) //Do not consider Total as a value to be plotted
            totalPosition = i;
    }
    if (totalPosition > -1)
        [dataArray removeObjectAtIndex:totalPosition];
    
    return [dataArray copy];
}

-(void)constructPieChart:(CPTGraphHostingView *) hostingView
{
    // Create pieChart from theme
    pieGraph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
    CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
    [pieGraph applyTheme:theme];
    hostingView.hostedGraph             = pieGraph;
    pieGraph.plotAreaFrame.masksToBorder = NO;
    
    pieGraph.paddingLeft   = 0.0;
    pieGraph.paddingTop    = 300.0;
    pieGraph.paddingRight  = 10.0;
    pieGraph.paddingBottom = 10.0;
    
    pieGraph.axisSet = nil;
    
    CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle]; //Fix MC -- Added a title to the pieGraph
    titleStyle.color = [CPTColor whiteColor];
    titleStyle.fontName = @"Arial";
    titleStyle.fontSize = 16.0f;
    
    pieGraph.titleTextStyle = titleStyle;
    pieGraph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
    pieGraph.titleDisplacement = CGPointMake(0.0f, -16.0f);
    
    pieGraph.title = self.chartTitle;
    
    // Prepare a radial overlay gradient for shading/gloss
    CPTGradient *overlayGradient = [[CPTGradient alloc] init];
    overlayGradient.gradientType = CPTGradientTypeRadial;
    overlayGradient              = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.0] atPosition:0.0];
    overlayGradient              = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.3] atPosition:0.9];
    overlayGradient              = [overlayGradient addColorStop:[[CPTColor blackColor] colorWithAlphaComponent:0.7] atPosition:1.0];
    // Add pie chart
    piePlot                 = [[CPTPieChart alloc] init];
    piePlot.title = @"XYZ";
    piePlot.dataSource = self;
    piePlot.delegate = self;    
    piePlot.pieRadius       = 200;
    piePlot.identifier      = @"Therapy";
    piePlot.startAngle      = M_PI_4;
    piePlot.sliceDirection  = CPTPieDirectionCounterClockwise;
    piePlot.borderLineStyle = [CPTLineStyle lineStyle];
    piePlot.labelOffset     = 0;
    piePlot.overlayFill     = [CPTFill fillWithGradient:overlayGradient];
    [pieGraph addPlot:piePlot];
}

-(void)constructBarChart:(CPTGraphHostingView *) hostingView;
{
    
    // Create barChart from theme
    barChart = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
    
    CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
    [barChart applyTheme:theme];
    hostingView.hostedGraph             = barChart;
    barChart.plotAreaFrame.masksToBorder = NO;
    barChart.paddingLeft   = 70.0;
    barChart.paddingTop    = 300.0; //Fix MC -- padding 300 point from top inestead of just 20
    barChart.paddingRight  = 20.0;
    barChart.paddingBottom = 70.0;
    
    CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle]; //Fix MC -- Added a title to the barchart
    titleStyle.color = [CPTColor whiteColor];
    titleStyle.fontName = @"Arial";
    titleStyle.fontSize = 16.0f;
    
    barChart.titleTextStyle = titleStyle;
    barChart.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
    barChart.titleDisplacement = CGPointMake(0.0f, -16.0f);
    
    barChart.title = self.chartTitle;
    // Add plot space for horizontal bar charts
    
    // Need to set ranges from data for the graph to look nice
    
    float  xMax, yMax;
    xMax = yMax = 0.0f;
    
    Class cls = [CommonAPI class];
    NSArray *arrayData = [self removeTotalFromArray:self.chartArray];
    
    for (int i = 0; i < arrayData.count; i++)
        if ([((NSNumber *)[cls getValue:i graphDataArray:arrayData]) floatValue] > yMax)
            yMax = [((NSNumber *)[cls getValue:i graphDataArray:arrayData]) floatValue];
    
    CPTXYPlotSpace *plotSpace;
    
    plotSpace = (CPTXYPlotSpace *)barChart.defaultPlotSpace;
    
    //Fix MC -- yRange only 50% more than yMax inestead of twice as much
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromFloat(yMax *1.5)];
    
    
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)barChart.axisSet;
    CPTXYAxis *x          = axisSet.xAxis;
    x.axisLineStyle               = nil;
    x.majorTickLineStyle          = nil;
    x.minorTickLineStyle          = nil;
    x.majorIntervalLength         = CPTDecimalFromString(@"5");
    x.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");
    x.title                       = @"";
    x.titleLocation               = CPTDecimalFromFloat(7.5f);
    x.titleOffset                 = 45;
    x.labelRotation  = M_PI / 4;
    x.labelingPolicy = CPTAxisLabelingPolicyNone;
    
    NSMutableArray *treatmentLabels = [[NSMutableArray alloc] initWithCapacity:MAX_CAPACITY];
    
    for (int i = 0; i < arrayData.count; i++)
        [treatmentLabels addObject:[cls getGroup:i graphDataArray:arrayData]];
    
    NSArray *xAxisLabels         = [NSArray arrayWithArray:treatmentLabels];
    NSUInteger labelLocation     = 0;
    NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[xAxisLabels count]];
    
    NSMutableArray *customTickLocationsArray = [[NSMutableArray alloc] initWithCapacity:MAX_CAPACITY];
    
    // Add number of categories - Treatment labels  in graph
    //
    
    for (int i = 0; i < xAxisLabels.count; i++)
        if(!i)
            [customTickLocationsArray addObject:[NSDecimalNumber numberWithInt:1]];
        else
            [customTickLocationsArray addObject:[NSDecimalNumber numberWithInt:i*5]];
    
        
    xMax = xAxisLabels.count * 5; //Fix MC -- as this statement was missing, the bars used to overlap on the beginning of the x axis
    
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromFloat(xMax)];
    NSArray *customTickLocations = [NSArray arrayWithArray:customTickLocationsArray];
    
    for ( NSNumber *tickLocation in customTickLocations ) {
        CPTMutableTextStyle *textStyle = [[CPTMutableTextStyle alloc] init];
        textStyle.fontName = @"Arial";
        textStyle.fontSize = 10.0;
        textStyle.color = [CPTColor whiteColor];
        CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:[xAxisLabels objectAtIndex:labelLocation] textStyle:textStyle];
        labelLocation++;
        newLabel.tickLocation = [tickLocation decimalValue];
        newLabel.offset       = x.labelOffset + x.majorTickLength;
        newLabel.rotation     = M_PI / 8;
        [customLabels addObject:newLabel];
    }
    
    x.axisLabels = [NSSet setWithArray:customLabels];
    
    CPTXYAxis *y = axisSet.yAxis;
    y.axisLineStyle               = nil;
    y.majorTickLineStyle          = nil;
    y.minorTickLineStyle          = nil;
    
    
    // ScaleToFit is not working need to figure it out to do
    if (yMax > 1500)
        y.majorIntervalLength         = CPTDecimalFromString([NSString stringWithFormat:@"%f", yMax/10]);
    else
        y.majorIntervalLength         = CPTDecimalFromString([NSString stringWithFormat:@"%f", yMax/10]);
    
    y.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0");
    y.title                       = @"Value";
    y.titleOffset                 = 45.0f;
    y.titleLocation               = CPTDecimalFromFloat(5.0f);
    // First bar plot
    CPTBarPlot *barPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor redColor] horizontalBars:NO];
    barPlot.baseValue  = CPTDecimalFromString(@"0");
    barPlot.dataSource = self;
    barPlot.delegate = self;
    barPlot.barOffset  = CPTDecimalFromFloat(0.750f); // Fix MC -- make the first bar start inside the barplot so it is more legible
    barPlot.identifier = @"Bar Plot 1";

    [barChart addPlot:barPlot toPlotSpace:plotSpace];
    
    //[plotSpace scaleToFitPlots:barChart.allPlots];
}
#pragma mark -
#pragma mark CPTBarPlot delegate method

#pragma mark -
#pragma mark Plot Data Source Methods



-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
    NSArray *arrayData = [self removeTotalFromArray:self.chartArray];
    
    return [arrayData count];
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
    
    NSDecimalNumber *num = nil;
    NSArray *arrayData = [self removeTotalFromArray:self.chartArray];
    
    Class cls = [CommonAPI class];
    if ( [plot isKindOfClass:[CPTBarPlot class]] ) {
        switch ( fieldEnum ) {
            case CPTBarPlotFieldBarLocation:
                if (index == 0)
                    num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:1];
                else
                    num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index*5];
                break;
                
            case CPTBarPlotFieldBarTip:
                
                num = (NSDecimalNumber *)[cls getValue:index graphDataArray:arrayData];
                break;
        }
    }
    else if ( [plot isKindOfClass:[CPTPieChart class]] ) {
        
        if (index >= [arrayData count])
            return nil;
        
        if ( fieldEnum == CPTPieChartFieldSliceWidth ) {
            num = (NSDecimalNumber *)[cls getValue:index graphDataArray:arrayData];
        }
        else {
            num = (NSDecimalNumber *)[NSDecimalNumber numberWithUnsignedInteger:index];
        }
    }
    
    return num;
}

-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index
{
    
    static CPTMutableTextStyle *whiteText = nil;
    NSArray *arrayData = [self removeTotalFromArray:self.chartArray];
    
    Class cls = [CommonAPI class];
    if ( !whiteText ) {
        whiteText       = [[CPTMutableTextStyle alloc] init];
        whiteText.color = [CPTColor whiteColor];
    }
    
    CPTTextLayer *newLayer = nil;
    
    if ( [plot isKindOfClass:[CPTBarPlot class]] ) {
        
        unsigned long l = [[cls getValue:index graphDataArray:arrayData] longValue];
        
        newLayer = [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:@"%lu", (unsigned long)l] style:whiteText];
    }
    else if ( [plot isKindOfClass:[CPTPieChart class]] ) {
        
        unsigned long l = 0;
        
        l = [[cls getValue:index graphDataArray:arrayData] longValue];
        if (l) {
            CPTMutableTextStyle *textStyle = [[CPTMutableTextStyle alloc] init];
            textStyle.fontName = @"Arial";
            textStyle.fontSize = 10.0;
            textStyle.color = [CPTColor whiteColor];
            newLayer = [[CPTTextLayer alloc] initWithText:[NSString stringWithFormat:@"[%lu] %@",  (unsigned long)l, [cls getGroup:index graphDataArray:arrayData]] style:textStyle];
        }
        else
            newLayer = (id)[NSNull null];
    }
    
    
    return newLayer;
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (int) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.chartArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Legend";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    
    if (cell == nil) {
        NSArray *cellObjects = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
        cell = (UITableViewCell*) [cellObjects objectAtIndex:0];
    }
    
    
    NSArray *labels = [cell.contentView subviews];
    
    ((UILabel *)[labels objectAtIndex:0]).text = [[CommonAPI class] getGroup:indexPath.row
                                                              graphDataArray:self.chartArray];
    ((UILabel *)[labels objectAtIndex:1]).text = [NSString stringWithFormat:@"%@",
                                                  [[CommonAPI class] getValue:indexPath.row
                                                              graphDataArray:self.chartArray]];

    return cell;
}

@end
